package com.example.springboot.controller;

import com.example.springboot.common.Result;
import com.example.springboot.entity.User;
import com.example.springboot.service.IUserService;
import com.example.springboot.controller.request.UserPageRequest;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;
import javax.annotation.Resource;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @GetMapping("/list")//查询用户列表
    public Result list() {
        List<User> users = userService.list();
        return Result.success(users);
    }

    @GetMapping("/page") //分页查询用户列表
    public Result listByCondition(UserPageRequest userPageRequest) {

        return Result.success(userService.page(userPageRequest));
    }

    @PostMapping("/login") //登录验证
    public Result login(@RequestBody User user) {
        User loginUser = userService.login(user.getLoginId(), user.getPassword());
        if (loginUser != null) {
            return Result.success(loginUser);
        } else {
            return Result.error("登录ID或密码错误");
        }
    }

    @GetMapping("/{loginId}")
    public Result findById(@PathVariable String loginId) {
        User user = userService.findById(loginId);
        if (user != null) {
            return Result.success(user);
        } else {
            return Result.error("用户不存在");
        }
    }

    @PostMapping("/add")
    public Result save(@RequestBody User user) {
        String randomString = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
        user.setLoginId(randomString);
        userService.save(user);
        return Result.success("用户添加成功");
    }

    @PutMapping("/{loginId}") //修改用户信息
    public Result update(@PathVariable String loginId, @RequestBody User user) {
        user.setLoginId(loginId);
        userService.update(user);
        return Result.success("用户信息更新成功");
    }

    @DeleteMapping("/{loginId}") //删除用户的功能
    public Result delete(@PathVariable String loginId) {
        userService.delete(loginId);
        return Result.success("用户删除成功");
    }
}